#!/bin/bash/python
# _*_ coding: utf-8 _*_
# file： conn_dev
# date-time: 2023/5/19-17:20
# auth:hard work
# description
import telnetlib
import time

from tools_dev_and_sys.sys_secure.check_host_status import check_host_stat
from utils.log_util import ERROR
from loguru import logger

class TelnetClient:
    def __init__(self, host_ip, password):
        self.tn = telnetlib.Telnet()
        self.host_ip = host_ip
        self.password = password
        self.port = 23

    def login_host(self):
        print("Info: need open 'telnet server enable' for kungao(config-telnet)#  ")
        try:
            status = check_host_stat(self.host_ip)
            if status:
                print(self.host_ip, "is online")
            else:
                # print(self.host_ip, "is not online")
                raise self.host_ip + "is not online"
            self.tn.open(self.host_ip, port=self.port)
        except TimeoutError:
            ERROR.logger.error("warning", "%s连接失败，请检测协议栈是否启动。。" % self.host_ip)
            raise "connection fail "
        self.tn.read_until(b'password', timeout=5)
        self.tn.write(self.password.encode('utf-8') + b'\n')
        cmd_result = self.tn.read_very_eager().decode('utf-8')
        if "% Bad passwords, please re-enter your password!" in cmd_result:
            ERROR.logger.error('%s登录失败，密码错误，3分钟后再试' % self.host_ip)
            return "Bad passwords False"
        elif "can't connect" in cmd_result:
            ERROR.logger.error('%s登录失败，密码错误，3分钟后再试' % self.host_ip)
            return "connect False"
        else:
            print(('%s 登录成功!!! ' % self.host_ip))
        time.sleep(3)
        return True

    def execute_cmd(self, cmd):
        time.sleep(1)
        self.tn.write(cmd.encode('utf-8') + b'\n')
        cmd_result = self.tn.read_very_eager().decode('utf-8')
        logger.info("cli_return: %s" % cmd_result)
        return cmd_result

    def check_get_pwd(self):
        current_cwd = self.execute_cmd("\r\n")
        if "kungao#" in current_cwd:
            self.execute_cmd("config ter")
        elif "kungao(config)# " not in current_cwd:
            self.execute_cmd("exit")
            self.execute_cmd("config ter")
        elif "kungao(config-" in current_cwd:
            self.execute_cmd("exit")
            self.execute_cmd("config ter")
        else:
            self.execute_cmd("config ter")

    def close_tel(self):
        self.tn.close()


if __name__ == '__main__':
    """kungao(config-system)# telnet server enable """
    print("test now")
    client = TelnetClient("10.11.0.217", "root@123")
    client.login_host()
    client.execute_cmd("en")
    v = client.execute_cmd("pri ver")
    print(v)
    # client.execute_cmd(snake())
